<template>
    <div class="operator">
        <el-form :inline="true" :model="dataForm" @keyup.enter.native="search()">
          <el-row >
              <el-col :span="24" style="display:flex;justify-content: center;height: 35px;">
                <span style="font-size: 20px; color: #000;font-weight: bold;">红灯预警列表</span>
              </el-col>
          </el-row>
            <el-form-item >
               <div style="display: flex; align-items: center;">
                <span style="margin-right: 10px; white-space: nowrap; font-weight: 600"  >设备编号/名称：</span>
                <!-- <div style="margin-top: 15px;"> -->
                  <el-input placeholder="设备名称" v-model="dataForm.deviceName" class="input-with-select" clearable>
                    <el-select v-model="dataForm.deviceNumber" slot="prepend" placeholder="请选择" clearable @clear="handleClear" filterable>
                      <el-option  v-for="item in dataForm.options" :key="item.value" :label="item.deviceNumberList" :value="item.deviceNumberList"></el-option>
                    </el-select>
                  </el-input>
                </div>
            </el-form-item>
            
            <el-form-item >
              <div v-if="dataForm.isOperator === 1" class="button-group">
                <el-button @click="search()" icon="el-icon-search" slot="append"></el-button>
                <el-button type="primary" v-if="isAuth('dss:operator:apply')" @click="applyHandle()" :disabled="dataListSelections.length <= 0">批量申请</el-button>
                </div>

                <div v-else class="container" style="display: flex; align-items: center; justify-content: flex-start; width: 100%;">

                  <div class="fastSearch" style="display: flex;  gap: 200px;">
                <el-button @click="search()" icon="el-icon-search"></el-button>
                  <div class="fastSearch" :inline="true">

                <el-badge :value="dataForm.hasCode" class="item">
                  <el-button size="primary"  @click="seekCode"> 待诊断</el-button>
                </el-badge>

                <el-badge :value="dataForm.waitDeal" class="item" >
                  <el-button size="warning" icon="el-icon-search"  @click="waitConfirm()">已诊断</el-button>
                </el-badge>
                      </div>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <el-table
      :data="dataList" border v-loading="dataListLoading"
      @selection-change="selectionChangeHandle" style="width: 100%;" >
      <el-table-column type="selection" header-align="center" align="center" width="50" v-if="dataForm.isOperator === 1"></el-table-column>
      <el-table-column label="序号" align="center" type="index" :index="indexMethod" width="50"/>

      <el-table-column prop="deviceId" header-align="center"  align="center" label="故障设备编号" ></el-table-column>

      <el-table-column prop="deviceName"  header-align="center"  align="center"  label="故障设备名称"></el-table-column>

    <el-table-column prop="deviceModel" header-align="center" align="center" label="故障设备型号"></el-table-column>
    
    <el-table-column prop="lightStart" header-align="center" align="center" label="红灯开始时间" sortable></el-table-column>

      <el-table-column  header-align="center" align="center" label="红灯时长" sortable :sort-method="sortByredTime">
        <template slot-scope="scope">
          <span style="color: #ff0000; font-size: 16px;">
             {{ dynamicDuration(scope.row.lightStart, scope.row.lightOver) }}
             </span>
        </template>
      </el-table-column>

    <el-table-column  prop="repairStatus" header-align="center" align="center" label="维修状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.repairStatus===-1" size="small" type="danger">待维修</el-tag>
          <el-tag v-else-if="scope.row.repairStatus===0" size="small" type="info">维修中</el-tag>
          <el-tag v-else size="small">正常</el-tag>
        </template>
    </el-table-column>
      

    <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
        <template slot-scope="scope" >
          <div v-if="dataForm.isOperator === 1">
            <el-button v-if="isAuth('dss:operator:apply')" type="success"  round="100%" @click="applyHandle(scope.row.deviceId,scope.row.id)">申请维修</el-button>
          </div>
          <div v-else>
            <el-button type="primary" size="medium"  @click="repair(scope.row.deviceId,scope.row.id)" icon="el-icon-edit" plain v-if="scope.row.breakdownCode ===null">维修</el-button>
          <el-tooltip content="完成维修" placement="top" popper-class="custom-tooltip" >
            <el-button type="success" size="medium" @click="completion(scope.row.deviceId,scope.row.id)" v-if="scope.row.breakdownCode !=null" icon="el-icon-check" round>完成</el-button>
          </el-tooltip>
          </div>
       </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 维修弹窗 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    </div>
</template>
<style>
.container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.button-group {
  display: flex;
  align-items: center;
}

.fastSearch {
  display: flex;
  align-items: center;
}

.item {
  margin-left: 30px; /* 控制 badge 间距 */
}
 .el-select .el-input {
    width: 130px;
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .fastSearch {
  display: flex;
  gap: 10px;
}
</style>
<script>
import { method } from 'lodash'
import AddOrUpdate from './operator-add-or-update.vue'
import { has } from 'lodash'
export default {
    data() {
        return {
          dataForm: {
            deviceNumber: '',
            isOperator: 0,
            hasCode: 0,
            waitDeal: 0,
            deviceName: '',
            options:[]
          },
          liveTime: Date.now(), // 动态时间戳
          pageIndex: 1,
          pageSize: 10,
          totalPage: 0,
          dataListLoading: false,
          dataList: [],
          dataListSelections: [],
          addOrUpdateVisible: false,
          
        }
    },
    components: {
        AddOrUpdate
    },
    activated() {
      this.getDataList()
      this.seekCode()
      this.waitConfirm()
  },
 mounted() {
    this.timer = setInterval(() => {
      this.liveTime = Date.now() // 每秒更新时间戳
    }, 1000)
  },
  beforeDestroy() {
    clearInterval(this.timer) // 清理定时器
  },
    methods: {
        search() {
            console.log(this.dataForm.deviceNumber)
            this.pageIndex = 1
            this.getDataList()
        },
      getDataList() {
            this.dataListLoading = true
            this.$http({
                url: this.$http.adornUrl('/dss/operator/list'),
                method: 'get',
                params: this.$http.adornParams({
                    'page': this.pageIndex,
                    'limit': this.pageSize,
                  'deviceNumber': this.dataForm.deviceNumber,
                    'deviceName':this.dataForm.deviceName,
                    'isOperator':this.dataForm.isOperator
                })
            }).then(({ data }) => {
                if (data && data.code === 0) {
                  this.dataList = data.page.list
                    this.totalPage = data.page.totalCount
                  this.dataForm.isOperator = data.isOperator
                  this.dataForm.options = data.deviceNumberList
                    console.log(this.dataForm.options);
                    
                } else {
                    this.dataList = []
                    this.totalPage = 0
                }
                this.dataListLoading = false
            })
      },
      //按照红灯时长排序
      sortByredTime() {
          
        },
        // 多选
        selectionChangeHandle (val) {
            this.dataListSelections = val
      },
        // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
        this. seekCode()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
        this.seekCode()
         this.waitConfirm()
      },
         /** 自定义编号 */
        indexMethod(index){
            let pageNum = this.pageIndex - 1;
            if((pageNum!==-1 && pageNum!==0)){
                return (index + 1) + (pageNum  * this.queryParams.pageSize);
            }else{
                return (index + 1)
            }
      },
       //计算时间间隔
        dynamicDuration(startTime, endTime) {
          const start = new Date(startTime).getTime()
          const end = endTime ? new Date(endTime).getTime() : this.liveTime
          const diff = Math.max(end - start, 0) // 处理负数

          const days = Math.floor(diff / 86400000)
          const hours = Math.floor((diff % 86400000) / 3600000)
          const minutes = Math.floor((diff % 3600000) / 60000)
          const seconds = Math.floor((diff % 60000) / 1000)

          const pad = n => n.toString().padStart(2, '0')
          return `${days}天${pad(hours)}时${pad(minutes)}分${pad(seconds)}秒`
      },
        handleClear() {
            console.log('asd')
            this.pageIndex = 1
            this.getDataList()
      },
      //点击维修按钮的方法：新增一个
      repair(deviceId,id) {
        this.addOrUpdateVisible = true
          console.log(deviceId,id);
          this.$nextTick(() => {
          this.$refs.addOrUpdate.init(deviceId,id)
        })
      },
      //点击完成按钮的方法
      completion(deviceId,id) {
        console.log(deviceId,id)
        this.$confirm(`请确认已经对[设备编号=${deviceId}]完成了维修工作！`, '提示', {
          iconClass: "el-icon-question",
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showClose: true,
          type: 'warning'
        }).then(() => {
          // console.log(deviceId)
          this.$http({
            url: this.$http.adornUrl('/dss/operator/completion'),
            method: 'post',
            data: this.$http.adornData(id, false),
          }).then(({ data }) => {
            console.log(deviceId)
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duratiion: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
            })
          })
      },
        //申请维修
      applyHandle(deviceId, id) {
        var ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        var deviceIds = deviceId ? [deviceId] : this.dataListSelections.map(item => {
          return item.deviceId
        })
        this.$confirm(`确定对[设备编号=${deviceIds.join(',')}]进行[${deviceId ? '申请维修' : '批量申请'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
           showClose: true,
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/dss/operator/apply'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      //查找已经确认故障码的列表
    seekCode() {
      console.log(this.dataList);
      this.$http({
        url: this.$http.adornUrl('/dss/operator/seekCode'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records;
          this.totalPage = data.page.total;
          this.dataForm.hasCode = data.size;
          console.log(this.totalPage)
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      })
      .catch(error => {
        console.error("请求失败:", error);
        this.dataListLoading = false;
      });
    },
      //查找待维修的
      waitConfirm() {
        console.log(222)
        this.$http({
        url: this.$http.adornUrl('/dss/operator/waitConfirm'),
        method: 'get',
        params: this.$http.adornParams({
          'page': this.pageIndex,
          'limit': this.pageSize,
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.dataList = data.page.records;
          this.totalPage = data.page.total;
          this.dataForm.waitDeal = data.size;
          console.log(this.totalPage)
        } else {
          this.dataList = [];
          this.totalPage = 0;
        }
        this.dataListLoading = false;
      }).catch(error => {
        console.error("请求失败:", error);
        this.dataListLoading = false;
      });
      }
  },

}
</script>